package com.gf.common.staticer;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.annotation.PostConstruct;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.gf.common.util.SpringUtils;
import com.gf.message.service.MessageService;

/**
 * 存储 每个用户 未读消息 数
 * 
 * @author zhuguifeng guifeng.net@gmail.com
 * @version 创建时间：2013-6-16 上午9:35:01
 */
@Component
public class MessageRemainsHelper {

	private static MessageService messageService;

	private static Log log = LogFactory.getLog(MessageRemainsHelper.class);

	/**
	 * long:用户ID Int: 未读数
	 */
	private static ConcurrentMap<Long, Integer> map = new ConcurrentHashMap<Long, Integer>();

	@PostConstruct
	private void init() {
		log.info("初始化");
		messageService = SpringUtils.getBean("messageService");
		log.info("初始化->messageService:" + messageService);
	}

	/**
	 * 用户登入时强制初始化，重新读取数据<br>
	 * 并返回未读消息数
	 * 
	 * @param userId
	 */
	public static int initLogin(Long userId) {
		log.info("登入初始化->messageService:" + messageService);

		int num = 0;
		num = messageService.getNumberOfUnreadMessages(userId);
		map.put(userId, num);

		return num;
	}

	/**
	 * 得到未读消息
	 * 
	 * @param userId
	 * @return
	 */
	public static int getRemains(Long userId) {
		if (map.containsKey(userId)) {
			return map.get(userId);
		}
		// 从数据库中取
		if (messageService == null) {
			log.error("messageService is null");
			return 0;
		}
		int num = messageService.getNumberOfUnreadMessages(userId);
		// 更新map
		map.put(userId, num);

		return num;
	}

	/**
	 * 更新消息数量<br>
	 * 增加一条未读消息<br>
	 * 如果map不存在该key，说明该用户没有登入，直接pass
	 * 
	 * @param userId
	 * @return
	 */
	public static void updateRemainsByOne(Long userId) {
		if (!map.containsKey(userId)) {
			return;
		}

		int num = 0;
		num = getRemains(userId);

		map.put(userId, ++num);
	}

	/**
	 * 群发<br>
	 * 更新消息数量<br>
	 * 增加一条未读消息
	 * 
	 * @param userId
	 */
	public static void updateRemainsByOne(Long[] userIds) {

		if (userIds != null && userIds.length > 0) {
			for (long userId : userIds) {
				updateRemainsByOne(userId);
			}
		}
	}

	/**
	 * 读一条消息
	 * 
	 * @param userId
	 * @return
	 */
	public static int readMessageByOne(Long userId) {
		int num = 0;

		if (map.containsKey(userId)) {
			num = map.get(userId);
			if (num > 0) {
				--num;
				map.put(userId, num);
			}
		}

		return num;
	}

	/**
	 * 登出 移除
	 * 
	 * @param userId
	 */
	public static void removeRemains(Long userId) {
		if (map.containsKey(userId)) {
			map.remove(userId);
		}
	}
}
